package com.zeyi.chat.handler;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.dto.Chat;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.manager.StageManager;
import com.zeyi.chat.manager.UserManager;
import com.zeyi.chat.po.ChatGroup;
import com.zeyi.chat.views.Alert;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

import java.util.List;
import java.util.Map;

/**
 * @author zeyi
 */
public class AddHandler {
    private AddHandler() {
    }

    private static class Singleton {
        public static final AddHandler INSTANCE = new AddHandler();
    }

    public static AddHandler getInstance() {
        return AddHandler.Singleton.INSTANCE;
    }

    /**
     * 处理添加好友
     */
    @Mapping("addFriend")
    public void handleFriend(Message message) {
        if (message.getFlag()) {
            Map map = JSON.parseObject(message.getData(), Map.class);
            String type = (String) map.get("type");
            Chat friend = JSON.parseObject(((String) map.get("friend")), Chat.class);
            if (type.equals("0")) {
                new Alert("添加成功", StageManager.getFriendStage());
            }
            addChatList(friend);
        } else {
            new Alert("好友已存在", StageManager.getFriendStage());
        }
    }

    /**
     * 处理加群
     */
    @Mapping("joinGroup")
    public void handleGroupJoin(Message message) {
        if (message.getFlag()) {
            new Alert("加群成功", StageManager.getFriendStage());
            ChatGroup group = JSON.parseObject(message.getData(), ChatGroup.class);
            addChatList(new Chat(group.getId(), group.getGroupName(), group.getCreateId(), group.getAvatar(), group.getGroupCode()));
        } else {
            new Alert("你已经在群里面", StageManager.getFriendStage());
        }
    }

    /**
     * 处理建群
     */
    @Mapping("createGroup")
    public void handleGroupCreate(Message message) {
        ChatGroup group = JSON.parseObject(message.getData(), ChatGroup.class);
        new Alert("建群成功", StageManager.getGroupStage());
        addChatList(new Chat(group.getId(), group.getGroupName(), group.getCreateId(), group.getAvatar(), group.getGroupCode()));
    }

    /**
     * 添加聊天列表
     */
    private void addChatList(Chat chat) {
        Platform.runLater(() -> {
            List<Chat> list = UserManager.getCurrentUser().getChatList();
            list.add(chat);
            Stage primaryStage = StageManager.getPrimaryStage();
            ListView<Chat> chatList = (ListView<Chat>) primaryStage.getScene().getRoot().lookup("#chatList");
            chatList.setItems(FXCollections.observableArrayList(list));
        });
    }
}
